package lc20240428;

import java.util.ArrayList;
import java.util.List;

public class Ztransform {
    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        String res = Solution.convert(s, 3);
        System.out.println(res);
    }
}

class Solution {
    public static String convert(String s, int numRows) {

        int n = s.length();
        //如果是一行，或者要求的行数大于s的长度
        if (numRows == 1 || numRows>n) {
            return s;
        }
        List<StringBuilder> list = new ArrayList<>();

        int minNum = Math.min(numRows, n);
        for (int i = 0; i < minNum; i++) {
            list.add(i, new StringBuilder());
        }

        boolean flag = false;
        int num = 0;
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (num == 0 || num == numRows - 1) {
                //最最最重要的一句，设置一个旗帜，改变其中的布尔值，使得遍历顺序反向。
                flag = !flag;
            }
            list.get(num).append(c);
            num += flag ? 1 : -1;
        }
        //将list转为StringBuilder，就吧list理解为数组名，int[] a, 前面StringBuilder str就是int i;
        StringBuilder res = new StringBuilder();
        for (StringBuilder str : list) {
            res.append(str);
        }
        return res.toString();
    }
}